<template>
  <div id="vueapp">
    <!-- 弹幕开始-->
    <vue-baberrage
      :isShow="barrageIsShow"
      :barrageList="barrageList"
      :maxWordCount="maxWordCount"
      :throttleGap="throttleGap"
      :loop="barrageLoop"
      :boxHeight="boxHeight"
      :messageHeight="messageHeight"
      :lanesCount="lanesCount"
    >
    </vue-baberrage>
  · <!--弹幕结束-->

    <div class="card w100 headtop">
      <!--    头部推流信息展示start-->
      <div style="background-color: #282828;color: aliceblue" class="card-header font-weight-bold" id="header">
        教室名：{{ classroomName }}, 主播：{{ username }},

      </div>
      <!--    头部推流信息展示start-->
      <div class="box">
        <!--      流媒体展示start-->
        <div id="barrange-div" class="w100" style="height: 100%">
          <video id="video1" style="height: 100%;" class="videomain w100 disblock" controls autoplay
                 ref="preview"></video>
        </div>
        <!--      流媒体展示end-->

        <!-- 导航栏 start -->
        <div class="top w20">
          <ul class="nav nav-tabs w100" style="height: 4.5%;z-index: 20" role="tablist">
            <li v-on:click="LineOne=true,LineTow=false" role="presentation" class="active lineone w50">
              <a class="navtitle" href="#home" aria-controls="home" role="tab" data-toggle="tab">成员聊天</a>
              <div class="line w50" v-show="LineOne"></div>
            </li>
            <li v-on:click="LineOne=false,LineTow=true" role="presentation" class="active lineone w50">
              <a class="navtitle" href="#profile" aria-controls="profile" role="tab" data-toggle="tab">成员列表</a>
              <div class="line w50" v-show="LineTow"></div>
            </li>
          </ul>
          <div class="tab-content" style="height: 82%;width:100% ;">

            <div role="tabpanel" style="height: 100%;color: #ffffff" class="tab-pane active" id="home">
              <!--              <messagelist v-on:sendMessage="sendMessage" ref="message_list"></messagelist>-->
              <textarea style="color: #ffffff;resize: none;" id="msgArea" class="msgArea w100" rows="20"
                        v-model="areaMsgs" readonly>

                                </textarea>
              <textarea id="feedbackcontent" class="message w100" placeholder="请输入你的评论~" v-model="msg">
                                </textarea>
              <button class=" btn-primary"
                      style="font-size: 0.7vw;width:20%;height: 4%;position: absolute;right: 2px;bottom: 2px;border:none;outline:none;vertical-align:middle;text-align: center;"
                      v-on:click="sendMessage()" @keyup.enter="sendMessage()">发送
              </button>
            </div>
            <div role="tabpanel" class="tab-pane active" id="profile" v-show="LineTow">

              <client-list ref="client_list" :userlist="userlist"></client-list>
            </div>
          </div>
        </div>
        <!-- 导航栏 end -->
      </div>
    </div>
    <div>
<div>
<!--  功能按钮集合 start-->
  <button class="btn btn-primary" v-on:click="startRtmp()" :disabled="push"> 开始推流</button>
  <button class="btn btn-primary" v-on:click="stopRtmp()" :disabled="stoppush"> 停止推流</button>
  <button class="btn btn-primary" v-on:click="btnStartRecordClicked()"  :disabled="recording"> 开始录制</button>
  <button class="btn btn-primary" v-on:click="btnStopRecordClicked()" :disabled="!recording"> 停止录制</button>
  <el-input v-model="rtmpurl" placeholder="请输入推流地址" style="width: 150px;margin-left: 20px"></el-input>
  <button class="btn btn-primary" v-on:click="getCourse()" > 确定</button>

  弹幕：
  <el-switch v-model="state"
             active-value="1"
             inactive-value="2"
             @change="changestatus"
  >
  </el-switch>
  <button class="btn btn-primary" style="width: 150px;margin-left: 20px" v-on:click="stopClass()" :disabled="push"> 结束上课</button>
</div>
      <!--  功能按钮集合 end-->

    </div>
    <!--    提示框 start-->
    <div class="msg" v-show="showwarn">
      {{ warn }}
    </div>
    <!--    提示框 end-->
  </div>
</template>


<script>
const events = require('events');
const jQuery = window.jQuery = require("jquery");
const PlayerCanvas = require("./PlayerCanvas");
const Vue = require("vue/dist/vue");
const fs = require("fs");
const electron = require("electron");
const SCREEN_WIDTH = 1024;
const SCREEN_HEIGHT = 640;
require("../../components/Message/Message");
require("popper.js");
require("bootstrap");


const ipc = require('electron').ipcMain
const dialog = require('electron').dialog
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import clientList from "../../components/chat/Chat";

import SocketIO from "socket.io-client";
import VueSocketIO from "vue-socket.io";
import { exec,child_process } from "child_process";

import { vueBaberrage, MESSAGE_TYPE } from "vue-baberrage";
Vue.use(vueBaberrage);
//开启Socket连接
export default {
//页面进入
  beforeRouteEnter(to, form, next) {
    next();
    console.log("路由")
    Vue.use(new VueSocketIO({
      debug: true,
      connection: SocketIO('http://127.0.0.1:3333/') //xxx填后台给的socket地址，端口号根据实际后台端口写
    }))


  },
  //页面离开
  beforeRouteLeave(to, form, next) {
    next();
  },
  name: "push",
  created() {

    window.addEventListener("beforeunload", e => this.test(e));
  },
  components: {
    clientList
  },
  data() {
    return {
      columeTypeArr:[{
        value:'String',
        label:'字符串'
      },{
        value:'Int',
        label:'整数',
      },{
        value:'Decimal',
        label:'数值型'
      }],
      room: "123456",
      msg: "chenjinyin",
      barrageIsShow: true,
      show: false,
      messageHeight: 30,
      boxHeight: 412,
      barrageLoop: false,
      maxWordCount: 120,
      throttleGap: 5000,
      barrageList: [],
      lanesCount: 4,
      recording: false,
      SCREEN_WIDTH: 1024,
      SCREEN_HEIGHT: 640,
      classroomName: "高可用高并发",
      username: "陈锦银",
      LineOne: true,
      LineTow: false,
      areaMsgs: "欢迎进入我的直播间",
      userlist: [],
      lastTime: "",
      warn: "请不要连续点击",
      showwarn: false,
      barrage: ["陈锦银", "丁佳思", "测试"],
      state: "1",
      currentId: 0,
      workerProce:'',
      push:true,
      stoppush:true,
      rtmpurl:'',
      courseId:''
    };
  },
  beforeCreate() {

  },
   async mounted() {


    this._playerCanvas = new PlayerCanvas(SCREEN_WIDTH, SCREEN_HEIGHT);
    const textarea = document.getElementById("msgArea");
    textarea.scrollTop = textarea.scrollHeight;
    this.lists = [];
    // //创建房间


     this.IntiShow();
  },

  sockets: {
    connect: function() {
      console.log("开始链接服务器");
      this.websocketid = this.$socket.id;
      console.log(this.websocketid);
      console.log("开始登录");
    },
    disconnect() {
      console.log("断开服务器连接");
    },
    listClients(client) {
      this.userlist = client;
    },
    studentJoinedIn(data) {
      console.log(data + "学生加入");
      console.log(data);
    },
    gotMsg(username, content) {
      //用户消息
      this.areaMsgs += "\n";
      this.areaMsgs += (username[0] + ":" + username[1]);
      //弹幕显示
      this.barrageList.push({
        id: ++this.currentId,
        avatar: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3717120934,3932520698&fm=26&gp=0.jpg",
        msg: username[1],
        time: 6,
        type: MESSAGE_TYPE.NORMAL
      });
    }
  },
  methods: {
    stopClass(){
      // this.stoppush();
      this.$ajax.post("http://39.108.215.169:10239/api/services/app/Course/EndCourse", {

          FilterText:this.courseId,
          maxResultCount:100

      },{

        headers: {
          "accept": "text/plain",
          "Content-Type": "application/json-patch+json",
          "Authorization": "Bearer "+localStorage.getItem("token")
        }
      }).then((res) => {
        console.log(res)

        if (!res.data.success) {
          this.$message.error("课程结束失败！！");
          return;
        }
        else{
          //友好提示
          this.$message.success("课程已结束！！");
          //按钮控制
          this.joinClassRoom();
          this.push=false;
        }
      }).catch(err => {
        this.$message.success("结束上课失败");
        console.log(err);
        return;
      });
    },
    joinClassRoom(){
      this.$socket.emit("createClassroom", this.room, this.username, function(suc) {
        if (suc) {
          //成功
          console.log("创建房间成功");
          //this.room = name;
          this.username = "陈锦银";


        } else {
          console.log("创建失败");
        }
      });
    },
    getCourse(){
      let courseid=this.rtmpurl.slice(this.rtmpurl.lastIndexOf("/")+1,this.rtmpurl.length);
      this.courseId=courseid;
     console.log(localStorage.getItem("token"));
      if (courseid!=null) {
        this.$message.warning("正在获取课程具体信息中，请稍等！！");
        let url = "http://39.108.215.169:10239/api/services/app/Course/GetCourseNameById";
        this.$ajax.get(url, {
          params:{
            FilterText:courseid
          },
          headers: {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json",
            "Authorization": "Bearer "+localStorage.getItem("token")
          }
        }).then((res) => {
          if (!res.data.success) {
            this.$message.error("请输入正确的推流地址！！");
            return;
          }
          else{
            //友好提示
            this.$message.success("获取成功，请开始上课！！");
            //前台数据
            this.classroomName=res.data.result.courseName;
            this.username=res.data.result.teacherName;
            this.room=res.data.result.courseNumber;
            //按钮控制
            this.joinClassRoom();
            this.push=false;
          }
        }).catch(err => {
          this.$message.success("请检查上课地址");
          console.log(err);
          return;
        });
      }
    },
    //杀死进程
    stopRtmp(){
      var child_process = require('child_process');
      var chile = child_process.exec('"taskkill" /F /IM ffmpeg.exe* /T', function(error, stdout, stderr) {
        if (error) {
          console.error(`exec error: ${error}`);
          return;
        }
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
      });
    this.push=false;
    this.stoppush=true;
    },
    //发送消息
    sendMessages(room, content) {
      console.log("sendmsg..." + room + " " + content);
      console.log(this.$socket);
      this.$socket.emit("msg", room, content);
    },
    //socket初始化
    addSocketListeners() {
      this.$socket.on("listClients", clients => {
        //客户端列表
        this.userlist.push(clients);
      });
      this.$socket.on("gotMsg", (username, content) => {
        console.log("触发接收消息");
        //用户消息
        this.areaMsgs += "\n";
        this.areaMsgs += (username + ":" + content);
        //弹幕显示
        this.barrageList.push({
          id: ++this.currentId,
          avatar: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3717120934,3932520698&fm=26&gp=0.jpg",
          msg: content,
          time: 6,
          type: MESSAGE_TYPE.NORMAL
        });
      });

      this.$socket.on("studentJoinedIn", data => {
        console.log("学生加入" + data);
        // his._studentConnections.set(data.studentSid, new StudentConnection(this._socket, data.studentSid, this._mixedStream));
      });
      this.$socket.on("studentLeave", data => {
        console.log("学生加入" + data);
        // his._studentConnections.set(data.studentSid, new StudentConnection(this._socket, data.studentSid, this._mixedStream));
      });
    },
    //开启RTMP推流
    startRtmp() {
      this.stoppush=false;
      this.push=true;
// 任何你期望执行的cmd命令，ls都可以
      const cmdStr = "ffmpeg -f gdigrab -i desktop -f dshow -i audio=\"麦克风 (High Definition Audio Device)\" -s 1280x720 -r 20 -vcodec libx264 -preset ultrafast -acodec aac -ac 2 -ar 44100 -ab 128k -pix_fmt yuv420p -f flv "+this.rtmpurl;
      // 执行cmd命令的目录，如果使用cd xx && 上面的命令，这种将会无法正常退出子进程
      // const cmdPath = pathUtil.getAppResourcePath('')
      //console.log(cmdPath)
      // 执行命令行，如果命令不需要路径，或就是项目根目录，则不需要cwd参数：
       this._workerProcess = exec(cmdStr);
      // 不受child_process默认的缓冲区大小的使用方法，没参数也要写上{}：workerProcess = exec(cmdStr, {})

      // 打印正常的后台可执行程序输出
      this._workerProcess.stdout.on("data", function(data) {
        console.log("stdout: " + data);
      });

      // 打印错误的后台可执行程序输出
      this._workerProcess.stderr.on("data", function(data) {
        console.log("stderr: " + data);
      });

      // 退出之后的输出
      this._workerProcess.on("close", function(code) {
        console.log("out code：" + code);
      });
    },
    //改变状态弹幕是否显示
    changestatus() {
      this.barrageIsShow = !this.barrageIsShow;
    },
    //添加
    addToList() {
      this.barrageList.push({
        id: ++this.currentId,
        avatar: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3717120934,3932520698&fm=26&gp=0.jpg",
        msg: this.msg,
        time: 5,
        type: MESSAGE_TYPE.NORMAL
      });
    },
    //发送消息
    sendMessage() {
      let now = new Date().valueOf();
      console.log(now - this.lastTime);
      if (this.lastTime == 0 || (now - this.lastTime) > 3000) {
        //重置上一次点击时间，intervalTime是我自己设置的间隔时间，根据自己的需要传参
        this.lastTime = now;
        //添加自己要调用的方法
        this.sendMessages(this.room, this.msg);
        //this.$socket.emit("msg",{message:this.msg,username:this.username});

        this.msg = "";

      } else {
        this.showwarn = true;
        setTimeout(() => {
          this.showwarn = false;
        }, 3000);
      }


    },
    //初始化媒体
    async IntiShow() {
      this._stream = await navigator.mediaDevices.getUserMedia({
        video: false,
        audio: true
      });
      //获取视频
      this._screenStream = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: "desktop",
            minWidth: SCREEN_WIDTH,
            maxWidth: SCREEN_WIDTH,
            minHeight: SCREEN_HEIGHT,
            maxHeight: SCREEN_HEIGHT
          }
        }
      });

      //把视频轨道添加进入用户流中
      this._screenStream.getVideoTracks().forEach(value => {
        this._stream.addTrack(value);
      });
      this.$refs.preview.srcObject = this._screenStream;
    },
    async btnStartPush() {
      let p = child_process.spawn("ffmpeg", ["-fflags", "nobuffer", "-i", "-", "-vcodec", "libx264", "-f", "flv", this.rtmpurl]);
      p.stderr.on("data", data => {
        console.log(data.toString());
      });
      p.stdout.on("data", data => {
        console.log(data.toString());
      });

      let stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });

      let mr = new MediaRecorder(stream);
      mr.ondataavailable = async function(e) {
        p.stdin.write(NodeBuffer.from(await e.data.arrayBuffer()));
      };
      mr.start(40);

      p.once("exit", code => {
        mr.stop();
        console.log("杀死子进程")
        window.close();
      });
      setTimeout(()=>{

      },3000)
    },
    async btnStartRecordClicked(e) {

      // //this._stream = new MediaStream();
      // await this.attachAudioStream();
      // //this._cameraStream = await navigator.mediaDevices.getUserMedia({video: true, audio: false});
      // this._playerCanvas.setCameraVideo(this.createVideoElementWithStream(this._screenStream));
      //
      // this._screenStream = await navigator.mediaDevices.getUserMedia({
      //   audio: false,
      //   video: {
      //     mandatory: {
      //       chromeMediaSource: 'desktop',
      //       minWidth: SCREEN_WIDTH,
      //       maxWidth: SCREEN_WIDTH,
      //       minHeight: SCREEN_HEIGHT,
      //       maxHeight: SCREEN_HEIGHT
      //     }
      //   }
      // });
      await this.IntiShow();
      this._playerCanvas.setScreenVideo(this.createVideoElementWithStream(this._screenStream));

      let playerCanvasStream = this._playerCanvas.canvas.captureStream();
      playerCanvasStream.getTracks().forEach(t => this._stream.addTrack(t));
      this.$refs.preview.srcObject = playerCanvasStream;

      this.startRecord();
    },
    //附加流
    async attachAudioStream() {
      this._audioStream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
      this._audioStream.getAudioTracks().forEach(value => this._stream.addTrack(value));
    },
    //停止推流
    btnStopRecordClicked(e) {
      this.recording = false;
      this._recorder.stop();
    },
    //创建Video流用于录制视频
    createVideoElementWithStream(stream) {
      let video = document.createElement("video");
      video.autoplay = true;
      video.srcObject = stream;
      return video;
    },
    startRecord() {
      this._recorder = new MediaRecorder(this._stream, {mimeType: "video/webm;codecs=h264"});
      this._recorder.ondataavailable = async e => {
        let path = electron.remote.dialog.showSaveDialogSync(electron.remote.getCurrentWindow(), {
          title: "保存文件",
          defaultPath: "ScreenData.webm"
        });

        console.log(path);
        fs.writeFileSync(path, new Uint8Array(await e.data.arrayBuffer()));
      };
      this._recorder.start();
      this.recording = true;
    }
  }
};
</script>
<style>
body,
div,
h1,
span {
  /*background-color: #191919;*/
  color: #454445;
  border: none !important;
}

li {
  background-color: #2d2b2c !important;
}

textarea {
  background-color: #3b393a !important;
  border: none !important;
}

body {
  overflow: hidden;
}

.w100 {
  width: 100%;
}


.w50 {
  width: 50%;
}


.w30 {
  width: 30%;
}

.w20 {
  width: 20%;
}


.disblock {
  display: block;
}

#header {
  text-align: left;
}


.box {
  display: flex;
  flex-direction: row;
  position: relative;
}

.user {
  width: 120px;
  height: 40px;
  position: absolute;
  right: 20px;
  top: 0px;
  background-color: #282828;
  margin-top: 5px;
  padding-top: 100px;
}

.user .userimg {
  height: 40px;
  width: 42px;
  border-radius: 50%;
}

.user .username {
  position: absolute;
  left: 52px;
  top: 3px;
  color: white;
}

.top {
  background-color: #676161;
  position: relative;
}

.top .nav {
  color: white;
  width: 100%;
  height: 8%;
  border: none;
  position: relative;
}

.top .lineone {
  height: 100%;
  cursor: pointer;
  font-size: 1vw;
  text-align: center;
  border: none;
}

.top .navtitle {
  height: 100%;
  background-color: #2e2c2d !important;
  color: white !important;
  border: none !important;
  line-height: 30px;
  text-decoration: none;
}

.top .line {
  height: 3px;
  background-color: #419efe;
  position: absolute;
  bottom: 0px;

}

.box .title {
  color: white;
  position: absolute;
  left: 75px;
  top: 20px;
  font-size: 26px;
}

.tab-content .msgArea {
  width: 100%;
  height: 88%;
  margin-bottom: -6px;
  resize: none;
  background-color: #3b393a !important;
  border: 0;
  outline: none;
  overflow-x: hidden;
}

.tab-content .message {
  width: 100%;
  height: 15%;
  resize: none;
  font-size: 1em;
  color: wheat;
  background-color: #676161 !important;
  border: 0;
  outline: none;
  color: white !important;
  text-indent: 12px;
  overflow-y: hidden;
}


.btn {
  margin-left: 5%;
}

.msg {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 10px;
  animation: TipLayer 2s;
}


.g-scrollview {
  position: absolute;
  top: 4rem;
  left: 0.3rem;
}

.marquee_box {
  width: 100%;
  height: 2rem;

  color: #fff;
  overflow: hidden;
  box-sizing: border-box;
}

.userLi {
  font-family: Adobe Heiti Std R;
  width: 100%;
  height: 0.8rem;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 0.6rem;
  padding: 0.2rem;
  text-align: left;
}

> img {
  width: 0.47rem;
  height: 0.47rem;

  border-radius: 50%;
  margin-right: 0.2rem;
}

> span {
  display: inline-block;
  vertical-align: middle;
  margin-right: 0.2rem;
  color: #fff;
}

.many-span {
  color: #ffde01;
}

.userIl {
  margin-left: 150px;
}

.button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 68px;
  margin: 50px auto 30px;
}

img {
  width: 100%;
}

.baberrage-item .normal {
  background-color: #ffffff !important;
}

.baberrage-lane {
  background-color: #ffffff !important;
}

.baberrage-stage {
  z-index: 999;
  height: 20vh !important;
}

.headtop {
  padding-top: 100px;
}
</style>